package local.blueheart.springcloud.rabbitmq.util;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class MessageBrokerHelper {

    private static final Logger LOGGER = LoggerFactory.getLogger(MessageBrokerHelper.class);

    private ConnectionFactory connectionFactory;

    private String host;

    private int port;

    private String vHost;

    private String username;

    private String password;

    public MessageBrokerHelper(String host, int port, String vHost, String username, String password) {
        this.host = host;
        this.port = port;
        this.vHost = vHost;
        this.username = username;
        this.password = password;
        connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(host);
        connectionFactory.setPort(port);
        connectionFactory.setVirtualHost(vHost);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
    }

    public Connection getConnection() {
        Connection connection = null;
        try {
            connection = connectionFactory.newConnection();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return connection;

    }

    public void closeConnection(Connection connection) {
        if(connection!=null) {
            try {
                connection.close();
            } catch (IOException e) {
               LOGGER.error("connection close failure",e);
            }finally {

            }
        }
    }

    public Channel getChannel(Connection connection,String exchange_name,String type){
        Channel channel = null;
        try {
            channel = connection.createChannel();
            channel.exchangeDeclare(exchange_name,type);

        } catch (IOException e) {
            LOGGER.error("channel new failure",e);
        }
        return channel;
    }

    public Channel getChannel(Connection connection,String queue_name) {
        Channel channel = null;
        try {
            channel = connection.createChannel();
            channel.queueDeclare(queue_name,false,false,false,null);

        } catch (IOException e) {
           LOGGER.error("channel new failure",e);
        }
        return channel;
    }


    public void closeChannel(Channel channel) {
        if(channel!=null){
            try {
                channel.close();
            } catch (IOException e) {
                LOGGER.error("channel close failure",e);
            } catch (TimeoutException e) {
                LOGGER.error("channel close failure",e);
            }finally {

            }
        }
    }

}
